package cn.walls1717.juc.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁测试
 *
 * @author walls1717
 * @since 2022/12/09 23:04
 **/
@Slf4j
public class ReentryLockDemo {

    static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        // m1();
        new Thread(()->{
            lock.lock();
            try {
                log.info("外层");
                lock.lock();
                try {
                    log.info("内层");
                } finally {
                    lock.unlock();
                }
            } finally {
                // 加锁与释放锁要一一匹配，否则在当前线程可以顺利执行，但是其它线程就无法获取到锁，一直处于阻塞状态。
                // lock.unlock();
            }
        }, "t1").start();

        new Thread(()->{
            lock.lock();
            try {
                log.info("外层");
                lock.lock();
                try {
                    log.info("内层");
                } finally {
                    lock.unlock();
                }
            } finally {
                lock.unlock();
            }
        }, "t2").start();

    }

    private static void m1() {
        final Object obj = new Object();
        new Thread(() -> {
            synchronized (obj) {
                log.info("外层");
                synchronized (obj) {
                    log.info("中层");
                    synchronized (obj) {
                        log.info("内层");
                    }
                }
            }
        }).start();
    }
}
